package cn.gbase.jiangsu.data.transfer.action;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.service.IdEntityService;

import cn.gbase.jiangsu.data.transfer.bean.Community;
import cn.gbase.jiangsu.data.transfer.bean.Company;
import cn.gbase.jiangsu.data.transfer.bean.CompanyUser;
import cn.gbase.jiangsu.data.transfer.bean.ForumReply;
import cn.gbase.jiangsu.data.transfer.bean.ForumTopic;
import cn.gbase.jiangsu.data.transfer.bean.Supplier;
import cn.gbase.jiangsu.data.transfer.service.CompanyService;
import cn.gbase.jiangsu.data.transfer.service.ForumO2SService;
import cn.gbase.jiangsu.data.transfer.service.SupplierService;

/**
 * 论坛管理功能（运营商与供货商之间）.
 * 
 */
@IocBean(args = { "refer:dao" })
@At("/forumO2S")
@Filters(@By(type = CheckSession.class, args = { "companyUser", "jsp:/companyIndex" }))
public class ForumO2SAction extends IdEntityService<CompanyUser> {

	@Inject
	private ForumO2SService forumO2SService;
	@Inject
	private CompanyService companyService;
	@Inject
	private SupplierService supplierService;

	public ForumO2SAction() {
		super();
	}

	public ForumO2SAction(Dao dao) {
		super(dao);
	}

	/**
	 * 分页查询主题（主题管理页面）.
	 * 
	 * @param currentPage
	 * @param groupId
	 * @param addTime
	 * @param keyword
	 * @param req
	 * @throws UnsupportedEncodingException
	 */
	@At("/listTopic")
	@Ok("jsp:/forumO2S/listTopic")
	public QueryResult listTopic(@Param("p") int currentPage, @Param("supplierId") int supplierId,
			@Param("title") String title, HttpServletRequest request, HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());
		// 供应商列表
		List<Integer> supplierIds = new ArrayList<Integer>();
		//是校区
		if (2 == communityReal.getCommunityType()) {
			supplierIds = supplierService.getSuppliersByCommunity(communityReal.getId());
		} else {
			supplierIds = supplierService.getSuppliers(loginUser.getCompanyId());
		}
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("supplierId", "" + supplierId);
		itemMap.put("title", title);
		request.setAttribute("formdata", itemMap);
		request.setAttribute("fromId", loginUser.getCompanyId());

		Set set = new HashSet();
		List<Integer> newList = new ArrayList<Integer>();
		for (Iterator iter = supplierIds.iterator(); iter.hasNext();) {
			Integer element = (Integer) iter.next();
			if (set.add(element))
				newList.add(element);
		}
		List<Supplier> supplierList = new ArrayList<Supplier>();
		for (Integer sid : newList)
			supplierList.add(supplierService.getSupplier(sid));
		request.setAttribute("supplierList", supplierList);

		return forumO2SService.getTopicList(currentPage, supplierId, title, loginUser.getCompanyId());
	}

	/**
	 * 跳转到查看主题页面（主题管理）.
	 */
	@At("/viewTopic")
	@Ok("jsp:/forumO2S/viewTopic")
	public void toViewTopic(@Param("topicId") int topicId, HttpServletRequest req) {

		// 主题
		ForumTopic topic = forumO2SService.getTopic(topicId);
		if (topic == null) {
			throw new RuntimeException("该主题不存在。");
		}
		req.setAttribute("topic", topic);

		//查看次数+1
		forumO2SService.updateTopicClick(topicId, topic.getClick() + 1);

		// 取得回复列表
		List<ForumReply> replyList = forumO2SService.getReplyList(topicId);
		req.setAttribute("replyList", replyList);

	}

	/**
	 * 跳转到添加主题页面（主题管理）.
	 */
	@At("/toAddTopic")
	@Ok("jsp:/forumO2S/editTopic")
	public void toAddTopic(HttpServletRequest req, HttpSession session) {
		CompanyUser u = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(u.getCompanyId());
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());
		// 供应商列表
		List<Integer> supplierIds = new ArrayList<Integer>();
		//是校区
		if (2 == communityReal.getCommunityType()) {
			supplierIds = supplierService.getSuppliersByCommunity(communityReal.getId());
		} else {
			supplierIds = supplierService.getSuppliers(u.getCompanyId());
		}
		Set set = new HashSet();
		List<Integer> newList = new ArrayList<Integer>();
		for (Iterator iter = supplierIds.iterator(); iter.hasNext();) {
			Integer element = (Integer) iter.next();
			if (set.add(element))
				newList.add(element);
		}
		List<Supplier> supplierList = new ArrayList<Supplier>();
		for (Integer sid : newList)
			supplierList.add(supplierService.getSupplier(sid));
		req.setAttribute("supplierList", supplierList);
	}

	/**
	 * 跳转到修改主题页面.
	 */
	@At("/toEditTopic")
	@Ok("jsp:/forumO2S/editTopic")
	public void toEditTopic(@Param("id") int id, HttpServletRequest req, HttpSession session) {
		CompanyUser u = (CompanyUser) session.getAttribute("companyUser");
		// 要修改的主题
		ForumTopic p = forumO2SService.getTopic(id);
		req.setAttribute("formdata", p);

		// 供应商列表
		List<Integer> supplierIds = supplierService.getSuppliers(u.getCompanyId());
		Set set = new HashSet();
		List<Integer> newList = new ArrayList<Integer>();
		for (Iterator iter = supplierIds.iterator(); iter.hasNext();) {
			Integer element = (Integer) iter.next();
			if (set.add(element))
				newList.add(element);
		}
		List<Supplier> supplierList = new ArrayList<Supplier>();
		for (Integer sid : newList)
			supplierList.add(supplierService.getSupplier(sid));
		session.setAttribute("supplierList", supplierList);
	}

	/**
	 * 保存主题.
	 * 
	 * @param sp
	 */
	@At("/saveTopic")
	@POST
	@Ok(">>:/forumO2S/listTopic")
	@Fail("jsp:/forumO2S/editTopic")
	public void saveTopic(@Param("..") ForumTopic Topic, HttpServletRequest req, HttpSession session) {
		CompanyUser u = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(u.getCompanyId());
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());
		// 供应商列表
		List<Integer> supplierIds = new ArrayList<Integer>();
		//是校区
		if (2 == communityReal.getCommunityType()) {
			supplierIds = supplierService.getSuppliersByCommunity(communityReal.getId());
		} else {
			supplierIds = supplierService.getSuppliers(u.getCompanyId());
		}
		Set set = new HashSet();
		List<Integer> newList = new ArrayList<Integer>();
		for (Iterator iter = supplierIds.iterator(); iter.hasNext();) {
			Integer element = (Integer) iter.next();
			if (set.add(element))
				newList.add(element);
		}
		List<Supplier> supplierList = new ArrayList<Supplier>();
		for (Integer sid : newList)
			supplierList.add(supplierService.getSupplier(sid));
		req.setAttribute("supplierList", supplierList);
		forumO2SService.addOrUpdTopic(Topic, u.getCompanyId());
	}

	/**
	 * 删除主题（逻辑删除）.
	 */
	@At("/delete")
	@Ok("json")
	public String delete(@Param("id") int id) {
		forumO2SService.deleteTopic(id);
		return "{id:0}";
	}

	/**
	 * 删除主题（逻辑删除）.
	 */
	@At("/deleteMany")
	@Ok("json")
	public String deleteMany(@Param("idStr") String idStr) {
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			forumO2SService.deleteTopic(Integer.valueOf(id));
		}
		return "{id:0}";
	}

	/**
	 * 保存回复.
	 * 
	 * @param sp
	 */
	@At("/saveReply")
	@POST
	@Ok(">>:/forumO2S/viewTopic?topicId=${obj}")
	public int saveReply(@Param("..") ForumReply reply, HttpSession session) {
		CompanyUser u = (CompanyUser) session.getAttribute("companyUser");
		forumO2SService.addOrUpdateReply(reply, u.getCompanyId());
		return reply.getTopicId();
	}

}
